package com.tc.banana.framework;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Map.Entry;

import com.tc.banana.framework.annotation.Resource;
import com.tc.banana.framework.util.ReflectionUtil;

/** 
 * @author  wdd 
 * @date 创建时间：2016年4月3日 下午2:15:38 
 */
public final class IocHelper {
	
	static {
		init();
		Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
		for (Entry<Class<?>, Object> entry : beanMap.entrySet()) {
			Class<?> cls = entry.getKey();
			Object object = entry.getValue();
			for (Field field : cls.getDeclaredFields() ){
				if(field.isAnnotationPresent(Resource.class)){
					Resource resource = field.getAnnotation(Resource.class);
					String beanName = resource.value();
					Object instance = null;
					if (! "".equals(beanName.trim())) {
						// 根据名称注入
						instance = BeanHelper.getBean(beanName, beanMap);
					} else {
						if (field.getType().isInterface()){
							instance = BeanHelper.getInterfaceImplBean(field.getType(), beanMap);
						} else {
							instance = beanMap.get(field.getType());
						}
					}
					if (instance != null){
						ReflectionUtil.setField(object, field, instance);
					} else {
						throw new RuntimeException("can not set field of " + field.getName());
					}
				}
			}
		}
	}
	
	public static void init(){
		
	}
}
